<?php
namespace Common\Util;

use Common\Model\UserFanxianBalanceLogModel;
use Common\Model\UserModel;

class WechatAuth{

    /**
     * 获取access_token
     * @return mixed
     */
    public static function getAccessToken()
    {
        $app_system_setting = BaseData::getAppSetting();
        $access_token=S('wechat_access_token');

        if(!$access_token)
        {
            $url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$app_system_setting['wechat_appid'].'&secret='.$app_system_setting['wechat_appsecret'];
            $output=(array)json_decode(cyz_curl_get_contents($url));
            $access_token=$output['access_token'];
            S('wechat_access_token',$access_token,$output['expires_in'] - 300);
        }
        return $access_token;
    }

    /**
     * 获取jsapi_ticket
     * @return mixed
     */
    public static function getJsapiTicket()
    {
        $wechat_access_token = self::getAccessToken();

        $jsapi_ticket=S('wechat_jsapi_ticket');
        if(!$jsapi_ticket)
        {
            $url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$wechat_access_token.'&type=jsapi';
            $output=(array)json_decode(cyz_curl_get_contents($url));
            $jsapi_ticket=$output['ticket'];
            S('wechat_jsapi_ticket',$jsapi_ticket,$output['expires_in'] - 300);
        }
        return $jsapi_ticket;
    }

    /**
     * 获取jssdk
     * @return array
     */
    public static function getJssdkData(){
        //生成微信JSSDK参数
        $app_system_setting = BaseData::getAppSetting();
        $wechat_jsapi_ticket = self::getJsapiTicket();
        $jssdk_url = $_SERVER["REQUEST_SCHEME"].'://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        $jssdk_noncestr = md5(time().rand(111,999));
        $jssdk_timestamp = time();
        $jssdk_str = "jsapi_ticket=".$wechat_jsapi_ticket."&noncestr=".$jssdk_noncestr."&timestamp=".$jssdk_timestamp."&url=".$jssdk_url;
        $jssdk_signature = sha1($jssdk_str);
        $jssdk_param_data = array(
            'appId'=>$app_system_setting['wechat_appid'],
            'timestamp'=>$jssdk_timestamp,
            'nonceStr'=>$jssdk_noncestr,
            'signature'=>$jssdk_signature
        );
        return $jssdk_param_data;
    }

    /**
     * 获取微信openid  暂时不需要用了
     * @return mixed
     */
    public static  function getOpenID()
    {
        $app_system_setting = BaseData::getAppSetting();
        $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
        if(!isset($_GET['code']))
        {
            if($_POST)
            {
                $_SESSION['wechat_get_openid_post']=$_POST;
            }
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app_system_setting['wechat_appid'].'&redirect_uri='.$baseUrl.'&response_type=code&scope=snsapi_base#wechat_redirect';
            header("location:$url");
            exit();
        }
        if(isset($_GET['code']))
        {
            if($_SESSION['wechat_get_openid_post'])
            {
                $_POST=$_SESSION['wechat_get_openid_post'];
                extract($_POST,EXTR_SKIP);
            }
            $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_system_setting['wechat_appid'].'&secret='.$app_system_setting['wechat_appsecret'].'&code='.$_GET['code'].'&grant_type=authorization_code';
            $output=(array)json_decode(cyz_curl_get_contents($url));
            return $output['openid'];
        }
        return false;
    }

    /**
     * 微信公众号授权登陆
     * @param string $redirect_uri
     */
    public static  function wechatAuth($redirect_uri='',$go_url='')
    {
        $user_m = new UserModel();
        $user_fanxian_m = new UserFanxianBalanceLogModel();
        $app_system_setting = BaseData::getAppSetting();
        if(!isset($_GET['code']) && !isset($_GET['access_token']))
        {
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app_system_setting['wechat_appid'].'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
            header("location:$url");
            exit();
        }
        if(isset($_GET['code']))
        {
            $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_system_setting['wechat_appid'].'&secret='.$app_system_setting['wechat_appsecret'].'&code='.$_GET['code'].'&grant_type=authorization_code';
            $output=(array)json_decode(cyz_curl_get_contents($url));

            $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$output['access_token'].'&openid='.$output['openid'].'&lang=zh_CN';
            $output=(array)json_decode(cyz_curl_get_contents($url));
            if(!isset($output['errcode']))
            {
                $user_openid = $output['openid']?$output['openid']:'';
                $user_nickname = $output['nickname']?$output['nickname']:'';
                $user_headimg = $output['headimgurl']?$output['headimgurl']:'';
                $user_sex = $output['sex']?$output['sex']:1;
                $user_language = $output['language']?$output['language']:'zh-cn';
                $user_city = $output['city']?$output['city']:'';
                $user_province = $output['province']?$output['province']:'';
                $user_country = $output['country']?$output['country']:'';
                if(!$user_info = $user_m->getUserInfoByOpenId($output['openid'])){
                    $a_u_data['user_from'] = 'weixin';
                    $a_u_data['user_type'] = 1;
                    $a_u_data['user_openid'] = $user_openid;
                    $a_u_data['user_alipay_openid'] = '';
                    $a_u_data['user_nickname'] = $user_nickname;
                    $a_u_data['user_sex'] = $user_sex;
                    $a_u_data['user_language'] = $user_language;
                    $a_u_data['user_city'] = $user_city;
                    $a_u_data['user_province'] = $user_province;
                    $a_u_data['user_country'] = $user_country;
                    $a_u_data['user_headimg'] = $user_headimg;
                    $a_u_data['user_true_phone'] = '';
                    $a_u_data['user_phone_status'] = 0;
                    $a_u_data['user_card_id'] = '';
                    $a_u_data['user_token'] = '';
                    $a_u_data['user_token_expires'] = 0;
                    $a_u_data['user_auth_sign'] = '';
                    $a_u_data['user_auth_status'] = 0;
                    $a_u_data['user_email'] = '';
                    $a_u_data['add_time'] = time();
                    $a_u_data['update_time'] = time();
                    $insert_user_id = $user_m->add($a_u_data);
                    //新用户注册赠送
                    $user_reg_jiangli_fanxian_amount = $app_system_setting['user_reg_jiangli_fanxian_amount']?$app_system_setting['user_reg_jiangli_fanxian_amount']:0;
                    if($user_reg_jiangli_fanxian_amount > 0){
                        $user_fanxian_m->addMoney($insert_user_id,0,12,$user_reg_jiangli_fanxian_amount,'','USER_REG_'.$insert_user_id);
                    }
                }else{
                    $insert_user_id = $user_info['id'];
//                    $s_u_data['user_nickname'] = $user_nickname;
//                    $s_u_data['user_sex'] = $user_sex;
//                    $s_u_data['user_language'] = $user_language;
//                    $s_u_data['user_city'] = $user_city;
//                    $s_u_data['user_province'] = $user_province;
//                    $s_u_data['user_country'] = $user_country;
//                    $s_u_data['user_headimg'] = $user_headimg;
//                    $user_m->where(['id'=>$insert_user_id])->save($s_u_data);
                }
                $user_m->updateUserPath($insert_user_id,cookie("referrer_user_id"));
                cookie('this_user_id',$insert_user_id,3600*2);
            }
            header("location:".$go_url);
            exit();
        }
    }

    /**
     * 微信公众号商家授权处理
     * @param string $redirect_uri
     */
    public static  function wechatAuthSign($redirect_uri='',$go_url='')
    {
        cookie('wechat_auth_openid',null);
        cookie('alipay_auth_openid',null);
        $app_system_setting = BaseData::getAppSetting();
        if(!isset($_GET['code']) && !isset($_GET['access_token']))
        {
            $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$app_system_setting['wechat_appid'].'&redirect_uri='.urlencode($redirect_uri).'&response_type=code&scope=snsapi_userinfo#wechat_redirect';
            header("location:$url");
            exit();
        }
        if(isset($_GET['code']))
        {
            $url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app_system_setting['wechat_appid'].'&secret='.$app_system_setting['wechat_appsecret'].'&code='.$_GET['code'].'&grant_type=authorization_code';
            $output=(array)json_decode(cyz_curl_get_contents($url));

            $url='https://api.weixin.qq.com/sns/userinfo?access_token='.$output['access_token'].'&openid='.$output['openid'].'&lang=zh_CN';
            $output=(array)json_decode(cyz_curl_get_contents($url));
            if(!isset($output['errcode']))
            {
                $wechat_auth_openid = $output['openid']?$output['openid']:'';
                //生成商家微信openid
                cookie('wechat_auth_openid',$wechat_auth_openid,3600*24);
            }
            header("location:".$go_url);
            exit();
        }
    }
}
